package com.hope.mychat.util;

import com.alibaba.fastjson.JSON;
import com.hope.mychat.domain.vo.Message;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by IDEA.
 * User: ZWH
 * Date: 2020/1/18
 * Time: 14:24
 * Desc: websocket工具类
 */
@Slf4j
public class WebSocketUtil {
    /**
     * 存储 websocket session
     */
    public static final Map<String, Session> LIVING_SESSIONS_CACHE = new ConcurrentHashMap<>();

    /**
     * 存储 websocket session
     */
    public static long ONLINE_COUNT = 0;

    /**
     * 普通信息
     *
     * @param uid 用户id
     * @param message 发送内容
     */
    public static void send(String uid, Message message) {
        Session session = LIVING_SESSIONS_CACHE.get(uid);
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        try {
            basic.sendText(JSON.toJSONString(message));
        } catch (IOException e) {
            log.error("===================== 发送消息错误");
            log.error("Message : ", message.toString());
            log.error(e.getMessage());
        }
    }

    /**
     * 心跳回应
     *
     * @param uid 用户id
     * @param message 发送内容
     */
    public static void pong(String uid, Message message) {
        send(uid, message);
    }

    /**
     * 普通消息
     *
     * @param uid 用户id
     * @param message 发送内容
     */
    public static void message(String uid, Message message) {
        send(uid, message);
    }

}
